package com.tyqx.hashchainutil.common;

import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

public class JsonUtil1 {

    /**
     * 对单层json进行key字母排序
     * @param json
     * @return
     */
    public static JSONObject getSortJson(JSONObject json){
        Iterator<String> iteratorKeys = json.keys();
        SortedMap map = new TreeMap();
        while (iteratorKeys.hasNext()) {
            String key = iteratorKeys.next().toString();
            Object vlaue = json.opt(key);
            map.put(key, vlaue);
        }
        JSONObject json2 = new JSONObject(map);
        return json2;
    }

    public static void main(String[] args) {
        String json="{\"donateId\":\"28837591274459917263\",\"donatee\":\"11\",\"plateNo\":\"222\",\"createTime\":\"2020-06-30 14:37:09\",\"outId\":\"18292028563043484903\",\"updateTime\":\"2020-06-30 14:37:09\",\"userName\":\"User10\",\"outTime\":\"2020-06-30 14:36:58\",\"operator\":\"222\",\"shipId\":\"222\"}";
        try {
            JSONObject jsonObject=new JSONObject(json);
            System.out.println(jsonObject.toString());
            JSONObject sortedJsonObject=getSortJson(jsonObject);
            System.out.println(sortedJsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getBody(HttpServletRequest request) throws IOException {
        String body = "";
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
        body = stringBuilder.toString();
        return body;
    }
}
